package com.jingdianjichi.interview.server.websocket;

import com.jingdianjichi.interview.server.config.websocket.WebSocketServerConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * ClassName:ChickenSocket
 * Package:com.jingdianjichi.circle.server.websocket
 * Description:
 *
 * @Author fst
 * @Create 2025/2/24 16:48
 * @Version 1.0
 */
@Slf4j
@ServerEndpoint(value = "/chicken/socket", configurator = WebSocketServerConfig.class)
@Component
public class ChickenSocket
{
    private static final AtomicInteger onlineCount = new AtomicInteger(0);

    private static final Map<String, ChickenSocket> clinets = new ConcurrentHashMap<>();

    private Session session;

    private String erp ="";

    public Session getSession(){return session;}


    @OnOpen
    public void onOpen(Session session, EndpointConfig conf) throws IOException
    {
        try {
            Map<String,Object> userProperties = conf.getUserProperties();
            String erp=(String) userProperties.get("erp");

            this.erp=erp;
            this.session=session;

            if(clinets.containsKey(this.erp))
            {
                clinets.get(this.erp).session.close();
                clinets.remove(this.erp);
                onlineCount.decrementAndGet();
            }

            clinets.put(this.erp,this);
            onlineCount.incrementAndGet();
            log.info("有链接加入：{},当前的在线人数是:{}", this.erp, onlineCount.get());

        } catch (Exception e)
        {
            log.error("websocket连接异常", e);
            return;
        }
    }

    @OnClose
    public void onClose()
    {
        try {
            if(clinets.containsKey(erp))
            {
                clinets.get(erp).session.close();
                clinets.remove(erp);
                onlineCount.decrementAndGet();
            }
            log.info("一个链接关闭，当前人数为:{}", onlineCount.get());
        } catch (IOException e) {
           log.error("链接异常,错误是：{}",e.getMessage());
        }
    }


    @OnMessage
    public void onMessage(String message, Session session)
    {
        log.info("服务器收到客户端[{}]的消息:{}",erp,message);

        //心跳机制
        if(message.equals("ping"))
        {
            try {
               this.sendMessage("pong",session);
            } catch (Exception e) {
                log.error("服务器向客户端[{}]发送消息失败,错误是:{}",erp,e.getMessage());
            }
        }
    }

    public void sendMessage(String message, Session session)
    {
        log.info("服务器向客户端[{}]发送消息:{}",erp, message);

        try {
            session.getBasicRemote().sendText(message);
        }catch (Exception e)
        {
            log.error("服务器向客户端[{}]发送消息失败,错误是:{}",erp,e.getMessage());
        }
    }

    @OnError
    public void onError(Session session, Throwable throwable)
    {
        log.error("链接发生错误,错误是:{}",throwable.getMessage());

        try {
            session.close();
        } catch (IOException e) {
            log.error("链接异常,错误是：{}",e.getMessage());
        }
    }

    public ChickenSocket getChickenSocket(String createdBy)
    {
        return clinets.get(createdBy);
    }
}
